package com.tz;

import org.apache.commons.dbcp.BasicDataSource;
import org.hibernate.SessionFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.orm.hibernate4.HibernateTransactionManager;
import org.springframework.orm.hibernate4.LocalSessionFactoryBean;
import org.springframework.transaction.annotation.EnableTransactionManagement;


import javax.sql.DataSource;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

/**
 * Created by Administrator on 16-7-26.
 */
@Configuration
@ComponentScan
@EnableAspectJAutoProxy//声明式事物的底层,所以也需要开启
@EnableTransactionManagement//启用声明式事物
public class WebAppConfig {
    //将组件配置放到容器中
    @Bean(name ="myList")//只要List类能够实例化,就能配到容器中,需要取个别名,Spring底层已经用了List
    //获得的时候根据别名获得
    public List  getList(){
        List<String> list=new ArrayList<String>();
        list.add("abc");
        list.add("hello");
        return  list;
    }
    @Bean//组件3
    public DataSource getDataSource(){
        //DataSource ds=new BasicDataSource();这里面向接口编程无法实例化
        BasicDataSource ds=new BasicDataSource();
        //初始化
        ds.setDriverClassName("org.h2.Driver");
        ds.setUrl("jdbc:h2:tcp://localhost/~/test");
        ds.setUsername("sa");
        ds.setPassword("");
        return  ds;
    }

    @Bean
    public LocalSessionFactoryBean getSessionFactory(){
        LocalSessionFactoryBean lsfb=new LocalSessionFactoryBean();
        //1.设置数据源
        lsfb.setDataSource(getDataSource());//配置数据源
        //2.设置属性 properties是一种特殊的map集合
        Properties props=new Properties();
        props.setProperty("hibernate.dialect","org.hibernate.dialect.H2Dialect");
        props.setProperty("hibernate.show_sql","true");
        lsfb.setHibernateProperties(props);
        //3.实体类注册信息
        lsfb.setPackagesToScan("com.tz.entity");
        return lsfb;
    }
    @Bean
    public HibernateTransactionManager tm(){
        HibernateTransactionManager tm= new HibernateTransactionManager();
        tm.setSessionFactory(getSessionFactory().getObject());
        return tm;
    }


}
